<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t("表单配置") }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('表名')" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          :placeholder="$t('表名')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item :label="$t(' 表说明')" prop="tableTxt">
        <el-input
          v-model="queryParams.tableTxt"
          :placeholder="$t(' 表说明')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item :label="$t('表类型 ')" prop="tableVersion">
        <el-select v-model="queryParams.tableType" placeholder="请选择" clearable>
          <el-option
            v-for="item in tableTyeOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="queryHandle"
        >{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("重置")
        }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t("新增") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:head:import']"
          type="primary"
          icon="el-icon-film"
          size="mini"
          @click="openImportTable"
        >{{ $t('导入表') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:head:import']"
          type="primary"
          icon="el-icon-upload"
          size="mini"
          @click="openImportJsonData"
        >{{ $t('导入数据') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:head:import']"
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="generateCode"
        >{{ $t('生成代码') }}</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-lollipop"
          size="mini"
          :disabled="btnDis"
          @click="sqlHandle"
        >{{ $t("SQL嵌入") }}</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-cpu"
          size="mini"
          :disabled="btnDis"
          @click="javaHandle"
        >{{ $t("JAVA嵌入") }}</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-time"
          size="mini"
          :disabled="btnDis"
          @click="viewHistorySql()"
        >{{ $t('版本SQL') }}</el-button>
      </el-col> -->
    </el-row>

    <el-table
      v-loading="loading"
      element-loading-text="正在加载请稍后"
      :data="onlCgformHeadList"
      border
      tooltip-effect="darkTable"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column
        :label="$t('序号')"
        type="index"
        align="center"
        show-overflow-tooltip
        width="50"
      >
        <template slot-scope="scope">
          {{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}
        </template>
      </el-table-column> -->
      <el-table-column
        type="selection"
        width="55"
        align="center"
        :selectable="canBeSelect"
      />
      <el-table-column :label="$t('表名')" align="center" prop="tableName" />
      <el-table-column :label="$t('表类型')" align="center" prop="tableTypeTxt" />
      <el-table-column :label="$t('表描述')" align="center" prop="tableTxt" show-overflow-tooltip />
      <el-table-column :label="$t('版本')" align="center" prop="tableVersion" />
      <el-table-column
        :label="$t('同步状态')"
        align="center"
        prop="isDbSynch"
      >
        <template slot-scope="scope">
          <div v-html="syncStatus(scope.row.isDbSynch)" />
        </template>
      </el-table-column>
      <!--      <el-table-column-->
      <!--        :label="$t('发布状态')"-->
      <!--        align="center"-->
      <!--        prop="releaseStatus"-->
      <!--      >-->
      <!--        <template slot-scope="scope">-->
      <!--          <div v-html="releaseStatus(scope.row)" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column :label="$t('发布目录')" align="center" prop="releaseAddress" show-overflow-tooltip />-->
      <el-table-column :label="$t('操作')" align="center" width="180">
        <template slot-scope="scope">
          <!-- <el-button
            v-if="scope.row.isDbSynch=='Y' && scope.row.tableType!=3"
            size="small"
            type="text"
            icon="el-icon-s-flag"
            @click="releaseHandle(scope.row)"
          >{{ $t("发布") }}</el-button> -->
          <el-button
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="updateHandle(scope.row)"
          >{{ $t("编辑") }}</el-button>
          <!-- 同步完数据库后才显示 -->
          <!-- <el-button
            v-if="scope.row.isDbSynch=='Y'"
            size="small"
            type="text"
            icon="el-icon-brush"
            @click="goPageHandle(scope.row)"
          >{{ $t("功能测试") }}</el-button> -->
          <el-divider direction="vertical" />
          <el-dropdown @command="handleCommand">
            <el-button size="small" type="text">{{ $t("更多") }}<i class="el-icon-arrow-down el-icon--right" /></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="scope.row.isDbSynch=='Y' && scope.row.tableType!=3">
                <a @click="releaseHandle(scope.row)">发布菜单</a>
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.isDbSynch=='N'">
                <a @click="dbSync(scope.row)">同步数据库</a>
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.isDbSynch=='Y'">
                <a @click="authConfig(scope.row)">权限配置</a>
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.isDbSynch=='Y'">
                <a @click="roleAuth(scope.row)">角色授权</a>
              </el-dropdown-item>
              <el-dropdown-item>
                <a @click="sortTableData(scope.row)">排序</a>
              </el-dropdown-item>
              <el-dropdown-item>
                <a @click="exportData(scope.row)">导出数据</a>
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.dataSources=='2' && scope.row.isDbSynch=='Y' && scope.row.tableType!=3 ">
                <a @click="deleteTable(scope.row)">清除数据</a>
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.isDbSynch=='Y' && scope.row.tableType!=3 ">
                <a @click="goPageHandle(scope.row)">功能测试</a>
              </el-dropdown-item>
              <el-dropdown-item>
                <a @click="delDb(scope.row, 'SC')">删除</a>
              </el-dropdown-item>
              <el-dropdown-item>
                <a @click="delDb(scope.row, 'YC')">移除</a>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改单开发对话框 -->
    <!-- custom-class="dialogForm" -->
    <!-- v-if="formOpen" -->
    <el-dialog
      v-if="formOpen"
      v-model="formOpen"
      :title="$t(title)"
      :visible.sync="formOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :fullscreen="true"
      append-to-body
    >
      <onlCgformHeadForm ref="onlCgformHeadForm" />
    </el-dialog>

    <el-dialog

      title="功能测试"
      :visible.sync="functionTestOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :fullscreen="true"
      append-to-body
    >
      <onlinePageList ref="onlineTestPage" />
    </el-dialog>

    <!-- 发布菜单 -->
    <el-dialog v-el-drag-dialog :title="$t('菜单列表')" modal-append-to-body :visible.sync="releaseListOpen" width="70%" custom-class="dialogForm" :close-on-click-modal="false" :lock-scroll="false">
      <div>
        <el-row>
          <el-col :span="24" style="margin-bottom: 20px;">
            <el-button type="primary" size="small" @click="addMenu(null)">新增</el-button>
          </el-col>
          <el-col :span="24">
            <el-table :data="menuList" border tooltip-effect="darkTable">
              <el-table-column :label="$t('菜单名称')" prop="menu.menuName" show-overflow-tooltip align="center" min-width="100" />
              <el-table-column :label="$t('发布位置')" prop="menu.scene" min-width="50" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.menu && scope.row.menu.scene === '0' ? 'PC端' : '移动端' }}</span>
                </template>
              </el-table-column>
              <el-table-column :label="$t('菜单类型')" prop="menu.menuType" :formatter="formatMenuType" min-width="100" align="center" />
              <el-table-column :label="$t('发布状态')" prop="status" align="center" min-width="100">
                <template slot-scope="scope">
                  <span v-if="scope.row.status === 'Y'" style="color: #67C23A">已发布</span>
                  <span v-else style="color:#F56C6C">未发布</span>
                </template>
              </el-table-column>
              <el-table-column :label="$t('发布目录')" prop="releaseAddress" show-overflow-tooltip min-width="180" />
              <el-table-column :label="$t('操作')" align="center" width="200">
                <template slot-scope="scope">
                  <el-button type="text" @click="addMenu(scope.row)">修改</el-button>
                  <el-button type="text" @click="delMenu(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <!-- 添加或修改菜单对话框 -->
    <el-dialog v-el-drag-dialog :title="$t('菜单')" modal-append-to-body :visible.sync="releaseOpen" width="70%" class="dataForm" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm">
      <div v-loading="formLoading">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('菜单场景')">
                <span slot="label">
                  {{ $t('菜单场景') }}
                  <el-tooltip :content="$t('如果视图布局，仅支持PC端')" placement="top">
                    <i class="el-icon-question" />
                  </el-tooltip>
                </span>
                <el-radio-group v-model="form.scene">
                  <el-radio label="0">{{ $t('PC端') }}</el-radio>
                  <el-radio label="1" :disabled="formStyle === 'view_style'">{{ $t('手机端') }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="height: 84px">
              <el-form-item :label="$t('菜单类型')" prop="menuType">
                <el-radio-group v-model="form.menuType">
                  <!--                  <el-radio label="M">{{ $t('目录') }}</el-radio>-->
                  <el-radio label="C">{{ $t('菜单') }}</el-radio>
                  <el-radio label="F">{{ $t('页签') }}</el-radio>
                  <el-radio label="Z">{{ $t('子页签') }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('上级菜单')">
                <treeselect v-model="form.parentId" :options="menuOptions" :show-count="true" :placeholder="$t('请选择')">
                  <label slot="option-label" slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }" :class="labelClassName">
                    {{ $t(node.label) }}
                    <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
                  </label>
                </treeselect>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('菜单名称')" prop="menuName">
                <el-input v-model="form.menuName" :placeholder="$t('菜单名称')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('菜单标识')" prop="menuKey">
                <el-input v-model="form.menuKey" :placeholder="$t('菜单标识')" />
              </el-form-item>
            </el-col>
            <el-col v-if="form.scene === '1'" :span="12">
              <el-form-item :label="$t('菜单图标Logo')">
                <UploadAvatar :logo-info="form.logoInfo" @appendData="uploadImg($event)" />
              </el-form-item>
            </el-col>
            <el-col v-else :span="12">
              <el-form-item :label="$t('菜单图标')">
                <el-popover placement="bottom-start" width="460" trigger="click" @show="$refs['iconSelect'].reset()">
                  <IconSelect ref="iconSelect" @selected="selected" />
                  <el-input slot="reference" v-model="form.icon" :placeholder="$t('菜单图标')" readonly>
                    <svg-icon v-if="form.icon" slot="prefix" :icon-class="form.icon" class="el-input__icon" style="height: 32px;width: 16px;" />
                    <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                  </el-input>
                </el-popover>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item :label="$t('显示排序')" prop="orderNum">
                <el-input-number v-model="form.orderNum" controls-position="right" :min="0" :max="9999" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <div style="margin: 10px auto;display: inline-block;width:100%;">
                <div class=" area-header">
                  <span class="area-header-title">{{ $t('菜单权限') }}</span>
                </div>
                <el-table :data="form.permissionList" border class="formTable">
                  <el-table-column :label="$t('序号')" align="center" type="index" width="50" />
                  <el-table-column :label="$t('名称')" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                      <el-form-item>
                        <el-input v-model="scope.row.name" :disabled="scope.row.disabled" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('权限标签')" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                      <el-form-item>
                        <el-input v-model="scope.row.permission" :disabled="scope.row.disabled" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('排序')" prop="sort">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.sort" controls-position="right" :precision="0" :disabled="scope.row.disabled" />
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('操作')" prop="sort">
                    <template slot-scope="scope">
                      <el-button type="text" icon="el-icon-delete" :disabled="scope.row.disabled" @click="deleteScope(scope.$index)" />
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <el-button type="primary" size="small" style="margin-top: 10px;margin-bottom: 10px;" @click="addScope">{{ $t('添加') }}</el-button>
            </el-col>
            <el-col :span="24">
              <div class="area-header">
                <span class="area-header-title">{{ $t("默认携带参数") }}</span>
              </div>
              <el-table :data="form.fieldList" class="componentTable" border tooltip-effect="darkTable">
                <el-table-column :label="$t('字段名')" prop="fieldId" show-overflow-tooltip align="center" min-width="100">
                  <template slot="header">
                    <span slot="label">
                      {{ $t('字段名') }}
                      <el-tooltip :content="$t('如果是主表字段直接写字段名称，如果是字表字段:表名.字段名')" placement="top">
                        <i class="el-icon-question" />
                      </el-tooltip>
                    </span>
                  </template>
                  <template slot-scope="scope">
                    <el-form-item :prop="'fieldList.'+scope.$index + '.fieldId'">
                      <el-input v-model="scope.row.fieldId" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('默认值')" align="center">
                  <template slot-scope="scope">
                    <el-form-item :prop="'fieldList.'+scope.$index + '.fieldValue'">
                      <el-input v-model="scope.row.fieldValue" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('操作')" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="delDefault(scope.$index,'value')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button size="small" type="primary" style="margin-top: 10px;margin-bottom: 10px;" @click="addDefault('value')">添加</el-button>
            </el-col>
            <el-col v-if="formStyle === 'view_style'" :span="24">
              <div class="area-header">
                <span class="area-header-title">{{ $t("查询条件") }}</span>
              </div>
              <el-table :data="form.conditionList" class="componentTable" border tooltip-effect="darkTable">
                <el-table-column :label="$t('字段名')" prop="fieldId" show-overflow-tooltip align="center" min-width="100">
                  <template slot-scope="scope">
                    <el-form-item :prop="'conditionList.'+scope.$index + '.fieldId'">
                      <el-select v-model="scope.row.fieldId">
                        <el-option v-for="item in fieldList" :key="item.name" :value="item.name" :label="$t(item.remark || item.name)" />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('条件')" align="center" prop="fieldCondition">
                  <template slot-scope="scope">
                    <el-form-item :prop="'conditionList.'+scope.$index + '.fieldCondition'">
                      <el-select v-model="scope.row.fieldCondition">
                        <el-option v-for="item in queryOptions" :key="item.dictValue" :value="item.dictValue" :label="$t(item.dictLabel)" />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('条件值')" align="center" prop="conditionValue">
                  <template slot-scope="scope">
                    <el-form-item :prop="'conditionList.'+scope.$index+'.conditionValue'">
                      <el-input v-model="scope.row.conditionValue" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('操作')" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="delDefault(scope.$index,'condition')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button size="small" type="primary" style="margin-top: 10px;margin-bottom: 10px;" @click="addDefault('condition')">添加</el-button>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">{{ $t("取消") }}</el-button>
          <el-button type="primary" @click="submitForm">{{ $t("发布") }}</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- sql增强弹出层 -->
    <el-dialog
      title="SQL增强"
      :visible.sync="sqlFormOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :fullscreen="true"
      append-to-body
    >
      <onlCgformEnhanceSqlList ref="onlCgformEnhanceSqlList" />
    </el-dialog>
    <!-- java增强弹出层 -->
    <el-dialog
      title="JAVA增强"
      :visible.sync="javaFormOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :fullscreen="true"
      append-to-body
    >
      <onlCgformEnhanceJavaList ref="onlCgformEnhanceJavaList" />
    </el-dialog>

    <import-the-template ref="import" @ok="handleQuery" />

    <el-dialog title="历史版本SQL" :visible.sync="historySqlformOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <onlCgformHeadRecordList ref="onlCgformHeadRecordList" />
    </el-dialog>
    <el-dialog
      title="自定义按钮"
      :visible.sync="btnFormOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      custom-class="dialogForm"
      append-to-body
    >
      <buttonProperty ref="buttonProperty" />
    </el-dialog>

    <el-dialog
      :title="$t('导入数据')"
      :visible.sync="upload.open"
      width="400px"
      :close-on-click-modal="false"
      :lock-scroll="false"
    >
      <div>
        <el-upload
          ref="upload"
          v-loading="upload.isUploading"
          :limit="1"
          accept=".json"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-exceed="handleFileExceed"
          :on-change="handleFileChange"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            {{ $t('将文件拖到此处，或') }}
            <em>{{ $t('点击上传') }}</em>
          </div>
          <div slot="tip" class="el-upload__tip" style="color:red">
            {{ $t('提示:仅允许导入"json"格式文件!') }}
          </div>
        </el-upload>

        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button @click="upload.open = false">{{ $t("取消") }}</el-button>
          <el-button type="primary" @click="submitFileForm">{{ $t("确定") }}</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="权限配置"
      :visible.sync="drawerOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
      width="60%"
      custom-class="dialogForm"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="字段权限" name="1">
          <OnlCgformAutoPage ref="onlCgformAutoPage" :data-id="rowId" />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog
      title="角色授权"
      :visible.sync="roleAuthOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
      :fullscreen="true"
    >
      <OnlCgformRoleAuth ref="onlCgformRoleAuth" :data-id="rowId" />
    </el-dialog>

    <el-dialog
      title="字段排序"
      :visible.sync="sortOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
      width="60%"
      custom-class="dialogForm"
    >
      <el-table
        ref="multipleTable"
        v-loading="sortLoading"
        max-height="500"
        :data="tableData"
        tooltip-effect="dark"
        row-key="id"
        @cell-mouse-enter.once="rowDrop"
      >
        <el-table-column :label="$t('#')" prop="index" align="center" width="50">
          <template slot="header">
            <el-tooltip class="item" effect="light" content="可拖拽排序" placement="top-start">
              <i class="el-icon-rank" />
            </el-tooltip>
          </template>
          <template>
            <span style="cursor:move;" class="handle">
              <i class="el-icon-rank" />
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="dbFieldTxt" label="字段备注" />
      </el-table>
      <div style="text-align: right;">
        <el-button type="primary" @click="saveSort">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOnlCgformHead, delOnlCgformHead, exportOnlCgformHead, syncDb, delDb, saveMenu, deleteByTableName, delDbDetails, saveSort } from '@/api/system/desform/onlineForm/onlCgformHead'
import Sortable from 'sortablejs'
import onlCgformHeadForm from './onlCgformHeadForm.vue'
import OnlCgformAutoPage from './onlCgformAutoPage.vue'
import OnlCgformRoleAuth from './onlCgformRoleAuth.vue'
import onlinePageList from '../release/onlinePageList.vue'
import onlCgformEnhanceSqlList from '../enhance/onlCgformEnhanceSqlList.vue'
import onlCgformEnhanceJavaList from '../enhance/onlCgformEnhanceJavaList.vue'
import buttonProperty from '@/components/desform/buttonProperty'
import { treeselect } from '@/api/system/menu'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import IconSelect from '@/components/IconSelect'
import importTheTemplate from './importTheTemplate'
import onlCgformHeadRecordList from './onlCgformHeadRecordList.vue'
import UploadAvatar from '@/components/Avatar/uploadAvatar'
import { downLoadZipOnl } from '@/utils/zipdownload'
import { getToken } from '@/utils/auth'

import {
  uploadAvatar
} from '@/api/system/menu'
import {
  delOnlComponentPath,
  getOnlComponentPath,
  listOnlComponentPath
} from '@/api/system/desform/componentPath/onlComponentPath'
import { getOnlViewConfigByHeadId } from '@/api/view/config/onlViewConfig'
const tableTye = [
        { value: '1', label: '单表' },
          { value: '2', label: '主表' },
            { value: '3', label: '子表' }
]
export default {
    components: {
        onlCgformHeadForm,
        onlinePageList,
        Treeselect,
        IconSelect,
        onlCgformEnhanceSqlList,
        onlCgformEnhanceJavaList,
        importTheTemplate,
        onlCgformHeadRecordList,
        buttonProperty,
        OnlCgformAutoPage,
        OnlCgformRoleAuth,
      UploadAvatar
    },
  data() {
      return {
          // 遮罩层
          loading: true,
          // 总条数
          total: 0,
          // 发布页面
          releaseOpen: false,
          sortOpen: false,
          sortLoading: false,
          dataList: [],
          headId: '',
          // 单开发表格数据
          onlCgformHeadList: [],
          // 弹出层标题
          title: '配置基本信息',
          // 功能测试
          functionTestOpen: false,
           // 菜单树选项
          menuOptions: [],
          visibleOptions: [],
          tableTyeOption: tableTye,
          // 是否显示弹出层
          formOpen: false,
          // sql增强弹出层
          sqlFormOpen: false,
          javaFormOpen: false,
          // 历史版本sql弹出层
          historySqlformOpen: false,
          btnFormOpen: false,
          // 发布菜单列表弹出层
          releaseListOpen: false,
          // 查询参数
          queryParams: {
              tableName: undefined,
              tableType: undefined,
              tableTxt: undefined,
              pageNum: 1,
              pageSize: 10
          },
          // 表单参数
          form: {
            // 菜单权限
            permissionList: []
          },
          // 表单校验
          rules: {
            releaseType: [
              { validator: this.validate, trigger: ['blur', 'change'] }
            ],
            isProject: [
              { validator: this.validateIsProject, trigger: ['blur', 'change'] }
            ],
            dealType: [
              { validator: this.validateDealType, trigger: ['blur', 'change'] }
            ]
          },
          multipleSelection: [],
          btnDis: true,
          upload: {
             // 是否显示弹出层（项目导入）
            open: false,
            // 弹出层标题（项目导入）
            title: '',
            // 是否禁用上传
            isUploading: false,
            // 设置上传的请求头部
            headers: { Authorization: 'Bearer ' + getToken() },
            // 上传的地址
            url: ''
          },
          drawerOpen: false,
          tableData: [],
          rowId: '',
          activeName: '1',
          roleAuthOpen: false,
          // 菜单列表
          menuList: [],
          tableName: '',
          tableTxt: '',
          isMobile: false,
        pathId: undefined,
        formLoading: true,
        formStyle: undefined,
        // 默认字段列表
        fieldList: [],
        queryOptions: [
          {
            dictValue: '=',
            dictLabel: this.$t('等于')
          },
          {
            dictValue: 'like',
            dictLabel: this.$t('包含')
          },
          {
            dictValue: '!=',
            dictLabel: this.$t('不等于')
          },
          {
            dictValue: '>',
            dictLabel: this.$t('大于')
          },
          {
            dictValue: '<',
            dictLabel: this.$t('小于')
          },
          {
            dictValue: '>=',
            dictLabel: this.$t('大于等于')
          },
          {
            dictValue: '<=',
            dictLabel: this.$t('小于等于')
          }
        ]
      }
  },
  computed: {
    guid() {
       return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          var r = Math.random() * 16 | 0
              var v = c === 'x' ? r : (r & 0x3 | 0x8)
          return v.toString(16)
      })
    }
  },
  created() {
      this.getList()
      this.getDicts('sys_show_hide').then(response => {
      this.visibleOptions = response.data
    })
  },
  mounted() {

  },
  methods: {
    /** 查询单开发列表 */
    getList() {
        this.loading = true
        listOnlCgformHead(this.queryParams).then(response => {
            this.onlCgformHeadList = response.rows
            this.total = response.total
            this.loading = false
        })
    },

    validate(rule, value, cb) {
      if (this.form.isProject === 'Y') {
        if (this.form.releaseType) {
          cb()
        } else {
          cb(new Error(this.$t('必填信息')))
        }
      } else {
        cb()
      }
    },
    validateIsProject(rule, value, cb) {
      if (this.form.isProject) {
        cb()
      } else {
        cb(new Error(this.$t('必填信息')))
      }
    },
    validateDealType(rule, value, cb) {
      if (this.form.dealType) {
        cb()
      } else {
        cb(new Error(this.$t('必填信息')))
      }
    },

    // 表单重置
    reset() {
       this.form = {
            id: undefined,
            name: undefined,
            uniqueKey: undefined,
            html: undefined,
            js: undefined,
            css: undefined,
            tableType: undefined,
            canvasStyle: undefined,
            magicalJsCodeData: undefined,
            isProject: 'N',
            releaseType: undefined,
            dealType: undefined,
            defaultCondition: undefined
        }
        this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
              tableName: undefined,
              tableType: undefined,
              tableTxt: undefined,
              pageNum: 1,
              pageSize: 10
          }
        this.resetForm('queryForm')
        this.queryHandle()
    },
    // 添加权限
    addScope() {
      if (!(this.form.permissionList instanceof Array)) {
        this.form.permissionList = []
      }
      var scope = {
          name: undefined,
          permission: undefined,
          sort: this.form.permissionList[this.form.permissionList.length - 1].sort + 1,
          disabled: false
      }
      this.form.permissionList.push(scope)
    },
    deleteScope(index) {
      this.form.permissionList.splice(index, 1)
    },
    /** 新增按钮操作 */
    addHandle() {
        this.formOpen = true
        this.$nextTick(() => {
            this.$refs.onlCgformHeadForm.init(null)
        })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
        this.formOpen = true
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            this.$refs.onlCgformHeadForm.init(row)
        })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(function() {
            return delOnlCgformHead(row.id)
        }).then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
        })
    },
    /** 导出按钮操作 */
    exportHandle() {
        const queryParams = this.queryParams
        this.$confirm(this.$t('是否确认导出数据项?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(function() {
            return exportOnlCgformHead(queryParams)
        }).then(response => {
            this.download(response.msg)
        }).catch(function() {
        })
    },
      syncStatus: function(status) {
        if (status === 'Y') {
        return ' <span style="color: #67C23A">已同步</span>'
        } else {
           return ' <span style="color:#F56C6C">未同步</span>'
        }
    },
    // 格式化菜单类型
    formatMenuType(row) {
      return row.menu ? (row.menu.menuType === 'C' ? this.$t('菜单') : row.menu.menuType === 'F' ? this.$t('页签') : this.$t('子页签')) : ''
    },
    releaseStatus: function(row) {
      if (row.tableType === 3) {
            return ' <span style="color:#909399">子表不具备发布功能</span>'
      } else {
      if (row.releaseStatus === 'Y') {
        return ' <span style="color: #67C23A">已发布</span>'
        } else {
           return ' <span style="color:#F56C6C">未发布</span>'
        }
      }
    },
    // 表单类型
     formType: function(type) {
        if (type === 1) {
        return '单表'
        } else if (type === 2) {
           return ' 主表'
        } else {
           return ' 子表'
        }
    },
    handleCommand() {

      }, dbSync(row) {
        this.$confirm('同步数据库, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
                this.loading = true
              syncDb(row.id).then(() => {
               this.$message({
                type: 'success',
                message: '同步成功!'
              })
              this.getList()
              this.loading = false
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消同步'
              })
            })
      },
      // 删除数据库
      delDb(row, status) {
        var del = '移除记录并删除数据表, 是否继续?'
        var successfully = '删除成功!'
        var calcel = '已取消删除'
        if (status === 'YC') {
          del = '移除记录, 是否继续?'
          successfully = '移除成功！'
          calcel = '已取消移除'
        } else if (row.dataSources === '1') {
          del = '是否确认删除?'
        }
        this.$confirm(del, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
             delDb(row.id, status).then(() => {
               this.$message({
                type: 'success',
                message: successfully
              })
              this.getList()
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: calcel
              })
            })
      },
      // 功能测试
      goPageHandle(row) {
        // 暂时不用路由跳转  改为弹出层
        // this.$router.push({ path: '/system/desform/onlineFormTestPage/onlineTestPage', query: { id: row.id }})
        // this.$store.dispatch('/system/desform/onlineFormTestPage/onlineTestPage', false)
         this.functionTestOpen = true
       this.$nextTick(() => {
          this.$refs.onlineTestPage.initData(row.id)
         })
      },

    /**
     * 新增菜单
     * @param row
     */
    addMenu(row) {
        this.releaseOpen = true
        console.log(row)
        this.resetMenuForm()
        if (row && row.id) {
          this.pathId = row.id
          this.formLoading = true
          getOnlComponentPath(row.id).then(res => {
            this.form.menuId = res.data.menu.id
            this.form.menuKey = res.data.menu.menuKey
            this.form.parentId = res.data.menu.parentId
            this.form.menuName = res.data.menu.menuName
            this.form.icon = res.data.menu.icon
            this.form.menuType = res.data.menu.menuType
            this.form.orderNum = res.data.menu.orderNum
            this.form.component = res.data.menu.component
            this.form.scene = res.data.menu.scene
            this.form.logoInfo = res.data.menu.logoInfo
            this.form.dealType = res.data.menu.dealType
            this.form.isProject = res.data.menu.isProject
            this.form.releaseType = res.data.menu.releaseType
            this.form.fieldList = res.data.fieldList && res.data.fieldList.length > 0 ? res.data.fieldList : this.form.fieldList
            this.form.conditionList = res.data.conditionList && res.data.conditionList.length > 0 ? res.data.conditionList : this.form.conditionList
            this.formLoading = false
          })
        } else {
          this.formLoading = false
          this.pathId = null
        }
      },
    /**
     * 删除菜单
     * @param row
     */
    delMenu(row) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delOnlComponentPath(row.id)
      }).then(() => {
        this.msgSuccess(this.$t('删除成功'))
        this.getMenuList()
      }).catch(function() {
      })
    },
      releaseHandle(row) {
        this.releaseListOpen = true
        this.headId = row.id
        this.tableName = row.tableName
        this.tableTxt = row.tableTxt
        this.isMobile = row.scene === '1'
        this.formStyle = row.formStyle
        this.getMenuList()
        this.getFieldList()
      // this.form.component = 'system/desform/release/onlineTestPage?queryId=' + row.id
    },
    getFieldList() {
      getOnlViewConfigByHeadId(this.headId).then(res => {
        if (res.data) {
          this.fieldList = res.data.fieldList
        }
      })
    },
    getMenuList() {
      // 查询已发布菜单
      listOnlComponentPath({ tempId: this.headId }).then(res => {
        this.menuList = res.rows
      })
    },
    resetMenuForm() {
      this.form = {
        menuId: undefined,
        menuKey: 'online:' + this.tableName,
        parentId: 0,
        menuName: this.tableTxt,
        icon: 'guide',
        menuType: 'C',
        orderNum: 1,
        isFrame: '1',
        visible: '0',
        scene: '0',
        logoInfo: undefined,
        fieldList: [],
        conditionList: [],
        permissionList: [
          {
            name: '编辑',
            permission: 'system:' + this.tableName + ':edit',
            sort: 1,
            disabled: true
          },
          {
            name: '删除',
            permission: 'system:' + this.tableName + ':remove',
            sort: 2,
            disabled: true
          },
          {
            name: '导出',
            permission: 'system:' + this.tableName + ':export',
            sort: 3,
            disabled: true
          }
        ]
      }
      this.form.component = 'system/desform/release/onlineTemplate?queryId=' + this.headId
      this.getTreeselect()
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.menuOptions = []
        const menu = {
          id: 0,
          label: this.$t('主类目'),
          children: []
        }
        menu.children = response.data
        this.menuOptions.push(menu)
      })
    },
    // 删除行
    delPermission(index) {
      this.form.permissionList.splice(index, 1)
    },
    AddRow() {
      const row = {
        name: '',
        permission: '',
        sort: this.form.permissionList.length + 1
      }
      if (this.form.component) {
        switch (this.form.permissionList.length) {
          case 0:
            row.name = '编辑'
            row.permission = this.form.component.split('/')[0] + ':' + this.form.component.split('/')[1] + ':edit'
            break
          case 1:
            row.name = '删除'
            row.permission = this.form.component.split('/')[0] + ':' + this.form.component.split('/')[1] + ':remove'
            break
          case 2:
            row.name = '导出'
            row.permission = this.form.component.split('/')[0] + ':' + this.form.component.split('/')[1] + ':export'
            break
        }
      }
      this.form.permissionList.push(row)
    },
    // 取消按钮
    cancel() {
      this.releaseOpen = false
      this.form = {}
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.scene === '1') {
            this.form.component = 'desform/release/onlineTemplate?queryId=' + this.headId
          }
          this.formLoading = true
          saveMenu(this.form, this.headId, this.pathId).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('发布成功'))
              this.cancel()
              this.getList()
              this.getMenuList()
              this.formLoading = false
            } else {
              this.msgError(response.msg)
              this.formLoading = false
            }
          })
        }
      })
    },
    // 选择图标
    selected(name) {
      this.form.icon = name
    },
    sqlHandle() {
        if (this.multipleSelection.length > 1) {
          this.$message({ message: '至多选择一条数据!', type: 'warning' })
          return
        }
        this.sqlFormOpen = true
        this.$nextTick(() => {
            this.$refs.onlCgformEnhanceSqlList.init(this.multipleSelection[0])
        })
    },
    javaHandle() {
        if (this.multipleSelection.length > 1) {
          this.$message({ message: '至多选择一条数据!', type: 'warning' })
          return
        }
        this.javaFormOpen = true
         this.$nextTick(() => {
            this.$refs.onlCgformEnhanceJavaList.init(this.multipleSelection[0])
        })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.btnDis = !(val.length > 0)
    },
    /** 导入后刷新页面 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      this.$refs.import.show()
    },
    /** 查看历史版本sql */
    viewHistorySql() {
      if (this.multipleSelection.length > 1) {
        this.$message({ message: '至多选择一条数据!', type: 'warning' })
        return
      }
      this.historySqlformOpen = true
      this.$nextTick(() => {
        this.$refs.onlCgformHeadRecordList.getList(this.multipleSelection[0])
      })
    },
    /** 清除数据库表 */
    deleteTable(row) {
      console.log(row.tableName)
      this.$confirm(this.$t('是否确认清除数据库?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return deleteByTableName(row.tableName)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('清除成功'))
      }).catch(function() {
      })
    },
    btnHandler() {
       if (this.multipleSelection.length > 1) {
          this.$message({ message: '至多选择一条数据!', type: 'warning' })
          return
        }
      this.btnFormOpen = true
      this.$nextTick(() => {
        this.$refs.buttonProperty.init(this.multipleSelection[0])
      })
    },
    // 上传图片
    uploadImg(data) {
      console.log()
      const formData = new FormData()
      formData.append('avatarfile', data)
      formData.append('id', this.form.id)
      uploadAvatar(formData).then(response => {
        if (response.code === 200) {
          this.form.logoInfo = response.msg
          this.msgSuccess(this.$t('修改成功'))
          this.$refs.uploadAvatar.open = false
        } else {
          this.msgError(response.msg)
        }
      })
    },
    exportData(row) { // 导出json数据
        this.$confirm('导出该配置表数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          downLoadZipOnl('/head/onlCgformHead/api/exportDataToJson/' + row.id)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消导出'
          })
        })
    },
    openImportJsonData() {
        this.upload.open = true
        this.upload.url = process.env.VUE_APP_BASE_API + '/head/onlCgformHead/api/importDataByJson'
    },
     submitFileForm() {
      this.$refs.upload.submit()
    },
     // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      if (response.code === 200) {
        this.msgSuccess(this.$t('导入成功'))
        this.getList()
      } else {
         this.msgError(response.msg)
      }
    },
     // 文件达到上限处理
    handleFileExceed() {
      this.msgError(this.$t('可上传文件数量已达到上限'))
    },
    // 文件上传变更时间
    handleFileChange(file, fileList) {
      if (!(file.name.indexOf('.json') >= 0)) {
        this.msgError(this.$t('仅允许导入".json"格式文件！'))
        fileList.splice(0, 1)
      }
    },
    authConfig(row) {
      this.drawerOpen = true
        this.$nextTick(() => {
            this.rowId = row.id
            this.$refs.onlCgformAutoPage.getFields(row.id)
        })
    },
    roleAuth(row) {
        this.roleAuthOpen = true
        this.rowId = row.id
         this.$nextTick(() => {
             this.$refs.onlCgformRoleAuth.refreshData()
         })
    },
    // 生成代码
    generateCode() {
      // console.log('this.multipleSelection', this.multipleSelection)
      //  generateTest(this.multipleSelection[0].id).then(response => {
      //     console.log(response)
      //  })
      if (this.multipleSelection.length === 0) {
        this.msgError(this.$t('请选择要生成的数据'))
        return
      } else if (this.multipleSelection.length > 1) {
        this.msgError(this.$t('最多只能选择一张表'))
        return
      }

      downLoadZipOnl('/onlGenerate/generateTest?headId=' + this.multipleSelection[0].id)
    },
    canBeSelect(row) {
      if (row.tableType === 1 || row.tableType === 2) {
        return true
      } else {
        return false
      }
    },
    // 添加默认值
    addDefault(type) {
      var obj = {}
      if (type === 'condition') {
        obj = {
          fieldId: undefined,
          conditionValue: '',
          fieldCondition: undefined
        }
        this.form.conditionList.push(obj)
      } else {
        obj = {
          fieldId: undefined,
          fieldValue: undefined
        }
        this.form.fieldList.push(obj)
      }
    },
    delDefault(index, type) {
      if (type === 'condition') {
        this.form.conditionList.splice(index, 1)
      } else {
        this.form.fieldList.splice(index, 1)
      }
    },
    rowDrop() {
      const tbody = this.$refs.multipleTable.$el.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        handle: '.handle',
        animation: 500,
        fallbackOnBody: true,
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0]
           _this.tableData.splice(newIndex, 0, currRow)
        //  _this.tableData = newArray
          _this.$forceUpdate()
          console.log(_this.tableData)
        }
      })
    },
    sortTableData(row) {
      this.sortOpen = true
      this.sortLoading = true
      this.$nextTick(() => {
        delDbDetails(row.id).then(response => {
           this.tableData = response.data.fields
           for (var i = 0; i < this.tableData.length; i++) {
            this.tableData[i]['index'] = i
           }

          //  this.tableData = []
          //   this.dataList.forEach(e => {
          //     const obj = {
          //       'id': e.id,
          //       'index': e.index,
          //       'dbFieldName': e.dbFieldName,
          //       'dbFieldTxt': e.dbFieldTxt,
          //       'dbDefaultVal': e.dbDefaultVal,
          //       'dbLength': e.dbLength,
          //       'dbIsNull': e.dbIsNull ? 1 : 0,
          //       'dbType': e.dbType,
          //       'dbPointLength': e.dbPointLength
          //     }
          //     this.tableData.push(obj)
          //   })
            this.sortLoading = false
        })
      })
    },
    saveSort() {
      const formData = { head: {}, fields: [], indexs: [] }
      formData.fields = this.tableData
      saveSort(formData).then(response => {
        if (response.code === 200) {
          this.$message('修改成功')
          this.sortOpen = false
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.el-dropdown {
  font-size: 12px;
}
/deep/.componentTable .el-form-item {
  min-height: unset !important;
}
</style>
